package www.openteam.com.ui.business;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.throrinstudio.android.common.libs.validator.Form;
import com.throrinstudio.android.common.libs.validator.Validate;

import java.util.ArrayList;
import java.util.Calendar;

import butterknife.Bind;
import butterknife.ButterKnife;
import www.openteam.com.R;
import www.openteam.com.adapter.CustomChildAdapter;
import www.openteam.com.bean.ApprovalStatu;
import www.openteam.com.bean.CustomOrder;
import www.openteam.com.bean.CustomType;
import www.openteam.com.bean.DeleteInfo;
import www.openteam.com.bean.OrderApprovalitem;
import www.openteam.com.bean.PackTypeInfo;
import www.openteam.com.bean.PbProductInfo;
import www.openteam.com.bean.SomeCustomInfo;
import www.openteam.com.contract.business.QryCstChildInfoContract;
import www.openteam.com.mvp.IPresenter;
import www.openteam.com.mvp.IView;
import www.openteam.com.presenter.business.QryCstChildInfoPresenter;
import www.openteam.com.rewrite.MNotEmptyValidator;
import www.openteam.com.tool.ToastUtil;
import www.openteam.com.ui.DetailedActivity;

import static www.openteam.com.tool.SplitXML.splitStringFloat;
import static www.openteam.com.tool.SplitXML.splitStringInt;
import static www.openteam.com.tool.SplitXML.splitStringString;

public class QryCstmChildInfoFragment extends Fragment implements
        View.OnClickListener, QryCstChildInfoContract.MView, IView {

    @Bind(R.id.qry_child_floatbar)
    FloatingActionButton floatbar;
    @Bind(R.id.qry_child_recycleview)
    RecyclerView mRecyclerView;

    private EditText dproductprice, printcolor, technicsinf,
            paperinf, wraptype, dsenddate,
            onum, dproductnumb, dproductname, dproductno;
    private ArrayList<OrderApprovalitem> orderApprovalitemList;
    private AlertDialog alertDialog;
    private CustomChildAdapter adapter;
    private QryCstChildInfoPresenter mPresenter;
    private int parentId = 0;
    private ProgressDialog mProgressDialog;
    private OrderApprovalitem approvalitem;
    private String TAG = this.getClass().getSimpleName();
    private IChildButtton iChildButtton;
    private int childPostion = 0;
    private boolean isChecked;

    public QryCstmChildInfoFragment() {
        // Required empty public constructor
    }

    public interface IChildButtton {

        void onclickSearch(int mark, int position);

        void onclickSearchPackType();

    }

    public void setChildButtton(IChildButtton childButtton) {
        this.iChildButtton = childButtton;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_qry_cstm_child_info, container, false);
        ButterKnife.bind(this, view);
        mPresenter = new QryCstChildInfoPresenter();
        if (mPresenter != null) {
            mPresenter.attachView(this);
        }
        initview();
        initListener();
        return view;
    }

    private void initListener() {
        floatbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(null);
            }
        });
        if (null != adapter) {
            adapter.setOnItemClickListener(new CustomChildAdapter.OnItemClickListener() {
                @Override
                public void onClickModify(int postion) {
                    childPostion = postion;
                    showDialog(orderApprovalitemList.get(postion));
                }
                @Override
                public void onClickDetele(int postion) {
                    OrderApprovalitem orderApprovalitem = orderApprovalitemList.get(postion);
                    mPresenter.deleteInfo(orderApprovalitem.getId(), orderApprovalitem.getProdno());
                }
            });
        }
    }

    private void initview() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        Log.e(TAG, "initview: isChecked  " + isChecked);
        adapter = new CustomChildAdapter(getContext(), orderApprovalitemList, isChecked);
        mRecyclerView.setAdapter(adapter);
    }

    public void getdata(CustomOrder.DataEntity dataEntity, boolean isInspect) {
        Log.e(TAG, "getdata: " + isInspect);
        parentId = dataEntity.getId();
        isChecked = isInspect;
        String[] prodname = dataEntity.getProdname().split(",");
        String[] prodno = dataEntity.getProdno().split(",");
        Float[] price = splitStringFloat(dataEntity.getPrice(), "price");
        Integer[] paynumb = splitStringInt(dataEntity.getPaynumb(), "paynumb");
        Integer[] othernumb = splitStringInt(dataEntity.getOthernumb(), "othernumb");
        String[] paperinf = splitStringString(dataEntity.getPaperinf(), "paperinf");
        orderApprovalitemList = new ArrayList<>();
        for (int i = 0; i < prodname.length; i++) {
//            Log.d(TAG, "onBindViewHolder:  for" +position);
            OrderApprovalitem orderApprovalitem = new OrderApprovalitem();
            orderApprovalitem.setId(dataEntity.getId());
            orderApprovalitem.setProdno(prodno[i]);
            orderApprovalitem.setProdname(prodname[i]);
            orderApprovalitem.setPaynumb(paynumb[i]);
            orderApprovalitem.setPrice(price[i]);
            orderApprovalitem.setOthernumb(othernumb[i]);
            orderApprovalitem.setPaperinf(paperinf[i]);
            orderApprovalitem.setPrintcolor(dataEntity.getPrintcolor());
            orderApprovalitem.setSenddate(dataEntity.getSenddate());
            orderApprovalitem.setWraptype(dataEntity.getWraptype());
            orderApprovalitem.setMark(i);
            orderApprovalitemList.add(orderApprovalitem);
        }


    }

    @Override
    public void onClick(View v) {
        if (iChildButtton != null) {
            switch (v.getId()) {
                case R.id.et_order_dproductname://产品名称1
                    iChildButtton.onclickSearch(parentId, childPostion);
                    break;
                case R.id.et_order_wraptype://包装方式
                    iChildButtton.onclickSearchPackType();
                    break;
            }
            ((DetailedActivity) getActivity()).searchFragmentClickEvent(new DetailedActivity.SearchFragmentButton() {
                @Override
                public void searchFramentButtonClick(PbProductInfo.DataEntity data, String info) {
                    dproductname.setText(data.getPbName());
                    dproductno.setText(data.getCode());
                    paperinf.setText(data.getPaperInf());
                    technicsinf.setText(data.getTechnicsinf());
                }

                @Override
                public void searchPackTypeInfoClick(PackTypeInfo.DataEntity dataEntity, String info) {
                    wraptype.setText(dataEntity.getName());
                }

                @Override
                public void searchCustomInfoClick(SomeCustomInfo.DataEntity dataEntity) {

                }

                @Override
                public void searchComtomTypeInfoClick(CustomType.DataBean customType, int type) {

                }
            });
        }
    }

    public void selectCalendar(final TextView v) {
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                v.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }

    private void showDialog(@Nullable final OrderApprovalitem orderApprovalitem) {
        View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_query_child_custom, null);
        dproductno = (EditText) view.findViewById(R.id.et_order_dproductno);//产品编号
        dproductname = (EditText) view.findViewById(R.id.et_order_dproductname);//产品名称1
        dproductprice = (EditText) view.findViewById(R.id.et_order_dproductprice);//价格
        dproductnumb = (EditText) view.findViewById(R.id.et_order_dproductnumb);//数量
        dsenddate = (EditText) view.findViewById(R.id.et_order_dsenddate);//送货日期
        wraptype = (EditText) view.findViewById(R.id.et_order_wraptype);//包装方式
        paperinf = (EditText) view.findViewById(R.id.et_order_paperinf);//产品材料1
        technicsinf = (EditText) view.findViewById(R.id.et_order_technicsinf);//工艺信息1
        printcolor = (EditText) view.findViewById(R.id.et_order_printcolor);//产品印色
        onum = (EditText) view.findViewById(R.id.et_order_onum);//备品数
        dproductname.setOnClickListener(this);
        wraptype.setOnClickListener(this);
        final Form form = new Form();
        addNotEmptyWidget(form,dproductno);
        addNotEmptyWidget(form,dproductname);
        addNotEmptyWidget(form,dsenddate);
//        addNotEmptyWidget(form,wraptype);
        dsenddate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectCalendar(dsenddate);
            }
        });
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setNegativeButton(R.string.quxiao, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setTitle("新建");
        approvalitem = new OrderApprovalitem();
        approvalitem.setMark(orderApprovalitemList.size());
        if (orderApprovalitem != null) {
            //添加
            builder.setTitle("修改");
            approvalitem.setMark(orderApprovalitem.getMark());
            dproductno.setText(orderApprovalitem.getProdno());
            dproductname.setText(orderApprovalitem.getProdname());
            dproductprice.setText(orderApprovalitem.getPrice() + "\t*\t" +
                    orderApprovalitem.getPaynumb() + "\t=\t" +
                    orderApprovalitem.getPrice() * orderApprovalitem.getPaynumb());
            paperinf.setText(orderApprovalitem.getPaperinf());
            wraptype.setText(orderApprovalitem.getWraptype());
            dsenddate.setText(orderApprovalitem.getSenddate());
            printcolor.setText(orderApprovalitem.getPrintcolor());
            technicsinf.setText(orderApprovalitem.getTechnicsinf());
            onum.setText(orderApprovalitem.getOthernumb() + "");
            dproductnumb.setText(orderApprovalitem.getPaynumb() + "");
        }
        builder.setView(view);
        alertDialog = builder.setPositiveButton(R.string.queding, null).create();
        alertDialog.show();
        Button button = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean validate = form.validate();
                if (validate) {//验证通过
                    createProgressDialog();
                    approvalitem.setId(parentId);
                    approvalitem.setProdno(dproductno.getText().toString());
                    approvalitem.setProdname(dproductname.getText().toString());
                    approvalitem.setPaynumb(Integer.parseInt(dproductnumb.getText().toString()));
                    approvalitem.setPrice(Float.parseFloat(dproductprice.getText().toString()));
                    if (onum.getText().toString().equals("")){
                        onum.setText("0");
                    }
                    approvalitem.setOthernumb(Integer.parseInt(onum.getText().toString()));
                    approvalitem.setPaperinf(paperinf.getText().toString());
                    approvalitem.setPrintcolor(printcolor.getText().toString());
                    approvalitem.setSenddate(dsenddate.getText().toString());
                    approvalitem.setWraptype(wraptype.getText().toString());

                    if (orderApprovalitem == null) {
                        //新建，添加
                        mPresenter.insertInfo(
                                parentId,
                                dproductno.getText().toString(),
                                wraptype.getText().toString(),
                                paperinf.getText().toString(),
                                dsenddate.getText().toString(),
                                technicsinf.getText().toString(),
                                printcolor.getText().toString(),
                                dproductnumb.getText().toString(),
                                onum.getText().toString(),
                                dproductprice.getText().toString()
                        );
                    } else {
                        //修改，更新
                        mPresenter.updateInfo(
                                parentId,
                                dproductno.getText().toString(),
                                wraptype.getText().toString(),
                                paperinf.getText().toString(),
                                dsenddate.getText().toString(),
                                technicsinf.getText().toString(),
                                printcolor.getText().toString(),
                                dproductnumb.getText().toString(),
                                onum.getText().toString(),
                                dproductprice.getText().toString(),
                                orderApprovalitem.getProdno()
                        );
                    }
                    alertDialog.dismiss();
                } else {//验证不通过
//                    ToastUtil.showToast(getContext(), "订单编号，价格，数量 ，送货日期不能为空");
                }
            }
        });

    }
    private void addNotEmptyWidget(Form form, TextView view) {
        Validate notEmpty = new Validate(view);
        notEmpty.addValidator(new MNotEmptyValidator(getContext(),R.string.notempty));
        form.addValidates(notEmpty);
    }
    private void createProgressDialog() {
        mProgressDialog = new ProgressDialog(getContext());
        mProgressDialog.setMessage("...正在更新,请您稍等...");
        mProgressDialog.show();
    }

    @Override
    public void deletSucces(DeleteInfo deleteInfo) {
        mProgressDialog.dismiss();
    }

    @Override
    public void deletFail(Throwable throwable) {
        Log.e(TAG, "deletFail: " + throwable.getMessage());
        mProgressDialog.dismiss();
    }

    @Override
    public void updateSucces(ApprovalStatu updateStatue) {
        orderApprovalitemList.remove(approvalitem.getMark());
        orderApprovalitemList.add(approvalitem.getMark(), approvalitem);
        mProgressDialog.dismiss();
    }

    @Override
    public void updateFail(Throwable throwable) {
        mProgressDialog.dismiss();
        Log.e(TAG, "updateFail: " + throwable.getMessage());
    }

    @Override
    public void insertSucces(ApprovalStatu insertStatus) {
        orderApprovalitemList.add(approvalitem);
        mProgressDialog.dismiss();
    }

    @Override
    public void insertFail(Throwable throwable) {
        mProgressDialog.dismiss();
        Log.e(TAG, "insertFail: " + throwable.getMessage());
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (alertDialog != null) {
            if (hidden) {
                alertDialog.hide();
            } else {
                alertDialog.show();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null)
            mPresenter.detachView();
    }
}
